package cn.woochen.comlib.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.jakewharton.rxbinding4.view.clicks
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import java.util.concurrent.TimeUnit

/**
 * 类描述：万能RecyclerView适配器
 * 创建人：woochen123
 * 创建时间：2017/5/23 18:32
 */
abstract class CommonRecyclerAdapter<T>(var mDatas: List<T>, var mLayoutId: Int, var clickTimeSecond: Long = 1L) :
        RecyclerView.Adapter<CommonRecyclerAdapter.ViewHolder>() {

    // 多布局支持
    private var mMultiTypeSupport: MultiTypeSupport<T>? = null

    //单击
    var mItemClickListener: OnItemClickListener? = null

    //长按
    var mLongClickListener: OnLongClickListener? = null

    //悬浮
    var mHoverListener: View.OnHoverListener? = null

    protected lateinit var mContext: Context

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        mContext = recyclerView.context
    }

    /**
     * 多布局支持
     */
    constructor(data: List<T>, multiTypeSupport: MultiTypeSupport<T>) : this(data, -1) {
        this.mMultiTypeSupport = multiTypeSupport
    }

    /**
     * 根据当前位置获取不同的viewType
     */
    override fun getItemViewType(position: Int): Int {
        return mMultiTypeSupport?.getLayoutId(mDatas[position], position)
                ?: super.getItemViewType(position)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        if (mMultiTypeSupport != null) {
            mLayoutId = viewType
        }
        val binding = DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(parent.context), mLayoutId, parent, false)
        return ViewHolder(binding)
    }

    @SuppressLint("CheckResult")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        if (mItemClickListener != null) {
            holder.itemView.clicks().throttleFirst(clickTimeSecond, TimeUnit.SECONDS).subscribeOn(AndroidSchedulers.mainThread()).subscribe {
                        mItemClickListener?.onItemClick(position)
                    }
        }
        if (mLongClickListener != null) {
            holder.itemView.setOnLongClickListener { mLongClickListener?.onLongClick(position)!! }
        }
        if (mHoverListener != null) {
            holder.itemView.setOnHoverListener { view, motionEvent -> mHoverListener?.onHover(view, motionEvent)!! }
        }
        convert(holder, getItem(position))
        holder.binding.executePendingBindings()
    }

    open fun getItem(position: Int): T {
        return mDatas[position]
    }

    override fun getItemCount(): Int {
        return mDatas.size
    }

    /**
     * 利用抽象方法回传出去，每个不一样的Adapter去设置
     * @param item 当前的数据
     */
    open fun convert(holder: ViewHolder, item: T) {

    }

    class ViewHolder(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {
        // 用来存放子View减少findViewById的次数
        private val mViews: SparseArray<View> = SparseArray()

        fun <DB : ViewDataBinding?> getDataBinding() = binding as DB

        /**
         * 设置TextView文本
         */
        fun setText(viewId: Int, text: CharSequence): ViewHolder {
            val tv = getView<TextView>(viewId)
            tv.text = text
            return this
        }

        /**
         * 通过id获取view
         */
        fun <T : View?> getView(viewId: Int): T {
            // 先从缓存中找
            var view: View? = mViews.get(viewId)
            if (view == null) {
                // 直接从ItemView中找
                view = itemView.findViewById(viewId)
                mViews.put(viewId, view)
            }
            return view as T
        }

        /**
         * 设置View的Visibility
         */
        fun setViewVisibility(viewId: Int, visibility: Int): ViewHolder {
            getView<View>(viewId).visibility = visibility
            return this
        }

        /**
         * 设置ImageView的资源
         */
        fun setImageResource(viewId: Int, resourceId: Int): ViewHolder {
            val imageView = getView<ImageView>(viewId)
            imageView.setImageResource(resourceId)
            return this
        }

        /**
         * 设置条目点击事件
         */
        fun setOnItemClickListener(listener: View.OnClickListener) {
            itemView.setOnClickListener(listener)
        }

        /**
         * 设置条目长按事件
         */
        fun setOnItemLongClickListener(listener: View.OnLongClickListener) {
            itemView.setOnLongClickListener(listener)
        }

        /**
         * 设置条目悬浮事件
         */
        fun setHoverListener(hoverListener: View.OnHoverListener) {
            itemView.setOnHoverListener(hoverListener)
        }

    }

}
